<template>
	<view class="content">
		<view style="height: 50px"></view>
		<canvas type="webgl" id="webgl"  style="width: 100%; height: 450px;"></canvas>
	</view>
</template>

<script>
	import { createScopedThreejs } from '../../threejs-miniprogram';
	import { registerGLTFLoader } from '../../loaders/gltf-loader';
	import { OrbitControls } from '../../threejs-miniprogram/OrbitControls';
	

	var camera, scene, renderer, model;
	var requestAnimationFrame;
	var controls 

	export default {
		data() {
			return {
				title: 'Hello'
			}
		},
		onReady() {
			let that = this;
			var query = wx.createSelectorQuery();
			query.select('#webgl').node().exec((res) => {
				var canvas = res[0].node;
				// 设置背景透明
				var gl = canvas.getContext('webgl', {
					alpha: true
				});

				if (canvas != undefined) {
					//  canvas.width 和canvas.style都需要设置，否则无法显示渲染
					canvas.width = canvas._width;
					canvas.height = canvas._height;
					requestAnimationFrame = canvas.requestAnimationFrame;
					that.init(canvas);
				}
			});
		},
		methods: {
			init(canvas) {
				let that = this;
				const THREE = createScopedThreejs(canvas)
				registerGLTFLoader(THREE)
				OrbitControls(THREE)
				//设置相机
				camera = new THREE.PerspectiveCamera(45, canvas.width / canvas.height, 0.25, 100);
				console.log('3333')
				
				console.log('3333')
				camera.position.set(-5, 3, 10);
				camera.lookAt(new THREE.Vector3(0, 2, 0));
				scene = new THREE.Scene();
				//设置光线
				var light = new THREE.HemisphereLight(0xffffff, 0x444444);
				light.position.set(0, 20, 0);
				scene.add(light);
				light = new THREE.DirectionalLight(0xffffff);
				light.position.set(0, 20, 10);
				scene.add(light);
				//加载外部模型
				var loader = new THREE.GLTFLoader();
				loader.load('https://cmc-data.oss-cn-shanghai.aliyuncs.com/RobotExpressive.glb', function(
				gltf) {
					model = gltf.scene;
					scene.add(model);
				}, undefined, function(e) {
					console.error(e);
				});
				renderer = new THREE.WebGLRenderer({
					antialias: true
				});
				controls = new THREE.OrbitControls( camera ,renderer.domElement);
				controls.autoRotate = true
				renderer.setSize(canvas.width, canvas.height);
				//调用动画
				that.animate();
			},

			animate() {
				// console.log('scene, camera',scene, camera)
				renderer.render(scene, camera);
				controls.update();
				requestAnimationFrame(this.animate);
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
		
	}
	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>
